package ag.script.project.standard.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ScriptImgPathScanner {


    //Map参数:key:js文件windows绝对路径,value:js文件当中的图片路径列表[key:原版脚本当中的安卓路径,value:需要替换成资源的安卓绝对路径]
    private final Map<File, List<ScriptResPaths>> imgsInJsCode;
    private final Map<String, String> duplicates;//去除重复的名称文件

    private final ScriptProject scriptProject;
    private final ScreensDes screensDes;

    private ScriptProjectStandardLog log;


    public ScriptImgPathScanner(String projectPath, ScreensDes screensDes) {
        this.imgsInJsCode = new ConcurrentHashMap<>();
        this.duplicates = new ConcurrentHashMap<>();
        this.scriptProject = new ScriptProject(projectPath, "", "");
        this.screensDes = screensDes;
        this.log = new ScriptProjectStandardLog(projectPath);
    }

    /**
     * 扫描脚本文件存在的资源列表
     *
     * @return 代码中的路径列表
     */
    public Map<File, List<ScriptResPaths>> start() {
        String projectPath = scriptProject.getProjectPath();
        List<File> jsFiles = FileUtil.loopFiles(projectPath, pathname -> StrUtil.endWithAnyIgnoreCase(FileUtil.extName(pathname), "js"));
        for (File jsFile : jsFiles) {
            List<ScriptResPaths> pathList_SingleCodeFile = getPathList(jsFile.getAbsolutePath());
            if (pathList_SingleCodeFile.isEmpty()) {
                continue;
            }
            imgsInJsCode.put(jsFile, pathList_SingleCodeFile);
        }
        return imgsInJsCode;
    }


    /**
     * 扫描脚本文件存在的资源列表
     *
     * @param codePath 脚本文件路径
     * @return 代码中的路径列表
     */
    private List<ScriptResPaths> getPathList(String codePath) {
        String projectName = scriptProject.getProjectName();
        String projectPath = scriptProject.getProjectPath();
        String imgsPath = new File(scriptProject.getFile_imgs(), screensDes.getName()).getAbsolutePath();
        //sdcard/Pictures/创造与魔法/.res/蒸汽石/全部拾取.png
        //(1)扫描脚本文件存在的资源列表
        List<ScriptResPaths> pathList = new ArrayList<>();
        List<String> codeList = ReUtil.findAllGroup1("\"([^\"]*)\"", FileUtil.readUtf8String(codePath));
        for (String codeLine : codeList) {
            if (StrUtil.containsAny(codeLine, "data/", "storage/", "sdcard/") && StrUtil.contains(codeLine, "/")) {
                if (StrUtil.endWithAny(codeLine, "png", "jpg", "jpeg")) {
                    String shortPath = StrUtil.subAfter(codeLine, projectName, true);
                    String imgFileName = FileUtil.getName(codeLine);


                    //加工成windows路径
                    File windowsFile = new File(projectPath, StrUtil.replace(StrUtil.removePrefix(shortPath, "/"), "/", "\\"));
                    String windowsFilePath = windowsFile.getAbsolutePath();

                    if (duplicates.get(imgFileName) == null) {
                        duplicates.put(imgFileName, windowsFilePath);
                    } else {
                        boolean hasRecord = false;
                        for (String imgName : duplicates.keySet()) {
                            String windowsDesPath_record = duplicates.get(imgName);
                            if (StrUtil.equals(windowsDesPath_record, windowsFilePath)) {
                                hasRecord = true;
                            }
                        }
                        //如果不存在一样的记录，那么就添加一个新的记录
                        if (!hasRecord) {
                            //如果不一样，但是名称相同，那么就取一个新的名称
                            File newNameFile = getNewNameFile(windowsFilePath);
                            windowsFilePath = newNameFile.getAbsolutePath();
                            imgFileName = FileUtil.getName(newNameFile);
                            duplicates.put(imgFileName, windowsFilePath);
                        } else {
                            duplicates.put(imgFileName, windowsFilePath);
                        }
                    }


                    //加工成windows目标路径
                    File windowsDesFile = new File(imgsPath, imgFileName);
                    String windowsDesPath = windowsDesFile.getAbsolutePath();

                    //加工成安卓路径
                    String androidPath = "/sdcard/Pictures/" + projectName + "/aigame-res/imgs/" + screensDes.getName() + "/" + imgFileName;

                    pathList.add(new ScriptResPaths(windowsFile.getAbsolutePath(), androidPath, codeLine, windowsDesPath));

                }
            }
        }
        return pathList;
    }

    //随机给新的文件取个新的名称
    public File getNewNameFile(String filePath) {
        String name = FileUtil.getName(filePath);
        String extName = FileUtil.extName(filePath);
        String parent = FileUtil.getParent(filePath, 1);
        if (StrUtil.contains(name, ".")) {
            name = StrUtil.subBefore(name, ".", true);
        }
        name = name + "_" + RandomUtil.randomNumbers(5);
        if (!StrUtil.isBlankIfStr(extName)) {
            name = name + "." + extName;
        }
        return new File(parent, name);
    }
}
